import axios from "axios";
import {an} from "vitest/dist/types-b7007192";
import {batch} from "~/logic/apis/taoCategory";
import {TRequest} from "~/utils/ali/PCRequest";
import {parseUrl} from "~/utils/util";

export default class Shop {

    public static getParams() {

        let input = document.querySelector('#J_ShopAsynSearchURL');
        if (!input) {
            window.location.href = location.origin + '/search.htm?analysis=true';
            return null;
        }else {
            let url = new URL(location.origin+input.value);
            let params = {};
            for (let [key, value] of url.searchParams) {
                params[key] = value;
            }
            params.viewType = 'grid';
            return params;
        }
    }

    public static getCid() {
        let path = this.getPath();
        let cid = path.match(/\/category-(\d+)\.htm/);
        return cid ? cid[1] : null;
    }

    public static async search(page: number = 1) {
        let params: {} = this.getParams();
        params.pageNo = page;
        let res = await axios.get(window.origin + '/i/asynSearch.htm', {
            params: params,
        });
        if (typeof res == 'undefined') {
            return false;
        }
        if (typeof res.data == 'object') {
            if (typeof res.data.url != 'undefined') {
                window.open(res.data.url)
                return false;
            }
        }
        const domParser = new DOMParser();
        // 去除转义字符
        res.data = res.data.replace(/\\"/g, '"');
        // <!--  item.discntPrice:  189.00     -->
        // 从html字符串中匹配所有价格
        let prices = res.data.matchAll(/item\.discntPrice:\s+(\d+\.\d+)/g);
        const dom = domParser.parseFromString(res.data, 'text/html');
        let result = this.getSearchGoodsResults(dom);
        prices = Array.from(prices);
        // 价格和商品id一一对应
        prices.forEach((item, index) => {
            // console.log(result[index], item[1])
            result[index].price = item[1];
        });
        let categoryIds = result.map((item) => {
            if (typeof item.categoryId === 'string') {
                return item.categoryId;
            }
        });
        batch(categoryIds);
        return {
            totalPage: this.getTotalPage(dom),
            currentPage: page,
            results: result,
        };
    }

    public static getSearchGoodsResults(dom: Document) {
        let results: any[] = [];
        const t = dom.querySelector(".shop-hesper-bd") || dom.querySelector(".J_TItems") || dom.querySelector(".shop-hesper-bd")
            , s = [].slice.call(t.children)
            , i = s.findIndex(e => "pagination" === e.getAttribute("class"))
            ,
            o = s.findIndex(e => -1 !== e.getAttribute("class").indexOf("item") || -1 !== e.getAttribute("class").indexOf("shop-list"))
            , a = s.slice(o, i).reduce((e, t) => [].concat(e, ...t.children), []);
        for (let e = 0, t = a.length; e < t; e++) {
            results.push(this.parseGoodDom(a[e]));
        }
        // 根据itemId去重
        results = results.filter(async (item, index, self) => {
            item.collectNum = await TRequest.counter(item.itemId);
            return self.findIndex((t) => {
                return t.itemId === item.itemId;
            }) === index;
        });
        return results;
    }

    public static parseGoodDom(e: any) {
        const t = e.querySelector(".photo a.J_TGoldData")
            , img = e.querySelector(".J_TGoldData img") || e.querySelector(".pic img")
            , name = e.querySelector(".J_TGoldData.item-name") || e.querySelector(".desc .permalink")
            , price = e.querySelector(".c-price") || e.querySelector(".price strong")
            , sale = e.querySelector(".sale-area") || e.querySelector(".sales-amount")
            , saleNum = e.querySelector(".sale-num") || e.querySelector(".sales-amount em")
            , itemId = e.dataset.id || e.querySelector(".pic a").attr("href").split("?")[1].match(/\d+/)[0]
            , c = t ? t.getAttribute("atpanel") : ""
            , category = c ? c.split(",")[2] : void 0
            , pic = img ? img.dataset.ksLazyload || img.src : ""
            , itemName = name ? name.innerText : ""
            , p = price ? price.innerText.replace("元", "") : 0;
        let totalSale, monthSale;
        if (sale) {
            sale.innerText.indexOf("总销量") > -1 ? totalSale = Number(saleNum.innerText.replace(/[^0-9]/gi, "")) : (monthSale = Number(saleNum.innerText.replace(/[^0-9]/gi, "")));
            if (typeof totalSale != "undefined" && sale.innerText.indexOf("万") > -1) totalSale = Number(totalSale + ''.replace(/[^0-9]/gi, "")) * 10000;
            if (typeof monthSale != "undefined" && sale.innerText.indexOf("万") > -1) monthSale = Number(monthSale + ''.replace(/[^0-9]/gi, "")) * 10000;
        }
        let commentNum = null;
        return {
            itemId: itemId,
            itemPic: pic,
            itemHref: "//item.taobao.com/item.htm?id=" + itemId,
            categoryId: category,
            itemName: itemName.trim(),
            price: Number(p.trim()),
            totalSale: totalSale,
            monthSale: monthSale,
            commentNum: commentNum,
            // 收藏
            collectNum: null,
        }
    }

    public static getTotalPage(dom: Document) {
        let totalPage = dom.querySelector(".ui-page-s-len") || dom.querySelector(".page-info");
        if (!totalPage) return 1;
        let i = totalPage?.innerHTML.indexOf('/');
        if (i === -1) return 1;
        return totalPage?.innerHTML.slice(i + 1);
    }

}
